package mo.org.cm309.shoppingcart.dao;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.sql.rowset.serial.SerialBlob;

import org.apache.log4j.Logger;

public class BaseDAO {
	
	private static Logger log = Logger.getLogger(BaseDAO.class);
	
    public BaseDAO() {

    }

    protected Connection getConnection() {
        try {
        	log.debug("Begin to connect to db...");
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/_3CShoppingCart");            
            return ds.getConnection();

        } catch (Exception ex) {
        	log.error(ex);
        }
        return null;
    }
   

    protected void releaseConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                log.debug("Closed db connection...");
            } catch (SQLException ex) {
            	log.error(ex);
            }
        }
        conn = null;
    }
    
    protected Blob bytes2Blob(byte[] bytes) {
    	try {
    		return new SerialBlob(bytes);
    	} catch (Exception ex) {
    		log.error(ex);
    	}
		return null;
    }
    
    protected byte[] image2ByteArray(Blob image) {
        if (image == null) {
            return null;
        }
        try {
        	int blobLength = (int) image.length();   
        	byte[] blobAsBytes = image.getBytes(1, blobLength);  
        	//release the blob and free up memory. (since JDBC 4.0) blob.free();
        	image.free();
        	return blobAsBytes;
        } catch (SQLException ex) {
        	log.error(ex);
        }
        return null;
    }
}
